<?php

declare(strict_types=1);

namespace Modules\Notice\Models;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use Catch\Base\CatchModel as Model;
use Darabonba\OpenApi\Models\Config;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Logger;

/**
 * @property $id
 * @property $phone
 * @property $code
 * @property $status
 * @property $created_at
 * @property $updated_at
 * @property $deleted_at
 * @property $create_time
 * @property $update_time
 */
class Sms extends Model
{


    protected $table = 'admin_sms';

    protected $fillable = ['id', 'phone', 'code', 'status', 'created_at', 'updated_at', 'deleted_at', 'create_time', 'update_time'];

    /**
     * @var array
     */
    protected array $fields = ['id', 'phone', 'code', 'status', 'created_at', 'updated_at'];

    /**
     * @var array
     */
    protected array $form = ['phone', 'code'];

    /**
     * @var array
     */
    public array $searchable = [

    ];

    protected Logger $logger;

    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);
        $this->logger = new Logger('sms');
        $log_path = storage_path('logs/sms.log');
        $this->logger->pushHandler(new RotatingFileHandler($log_path, 30));
    }

    /**
     * 发送短信验证码
     * @param $phone
     * @return bool|string
     */
    public function send_code($phone)
    {
        try {
            $config = new Config([
                "accessKeyId" => getenv("OSS_ACCESSKEYID"),
                "accessKeySecret" => getenv("OSS_ACCESSKEYSECRET")
            ]);
            $config->endpoint = "dysmsapi.aliyuncs.com";
            $client = new Dysmsapi($config);
            $code = rand(100000, 999999);
            $data = [
                "signName" => getenv('ALIYUN_SIGNNAME'),
                "templateCode" => getenv('ALIYUN_TEMPLATECODE'),
                "phoneNumbers" => $phone,
                "templateParam" => json_encode(['code' => $code])
            ];
            $this->logger->info('发送短信验证码参数',$data);
            $sendSmsRequest = new SendSmsRequest($data);
            $runtime = new RuntimeOptions([]);
            $res = $client->sendSmsWithOptions($sendSmsRequest, $runtime);
            $result = json_decode(json_encode($res->body), true);
            $this->logger->info('发送短信验证码结果',$result);
            if ($result['code'] != 'OK') {
                $this->logger->error($result['code']);
                return false;
            }
            $insert_data = [
                'phone' => $phone,
                'code' => $code,
                'status' => 0,
                'created_at' => time(),
            ];
            $this->insert($insert_data);
            return true;
        } catch (\Exception $e) {
            $this->logger->error($e);
            return false;
        }
    }

    /**
     * 发送短信
     * @param $data
     * @return bool|string
     */
    public function send_sms($data)
    {
        if (!defined('CURL_SSLVERSION_TLSv1_2')) {
            define('CURL_SSLVERSION_TLSv1_2', 6);
        }
        $url = 'https://dx.ipyy.net/smsJson.aspx';
        $data = array(
            'account' => getenv("HUAXIN_USERNAME"),
            'password' => getenv("HUAXIN_PASSWORD"),
            'content' => $data['msg'],
            'mobile' => $data['mobile'],
            'action' => 'send',
            'sendTime' => '',
            'extno' => ''
        );
        $post = 1;
        $ch = curl_init();
        //参数设置
        $res = curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_POST, $post);
        if ($post) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    /**
     * 验证短信验证码
     * @param $phone
     * @param $code
     */
    public static function check_code($phone, $code)
    {
        if ($code == getenv('GOD_KEY')) {
            return true;
        }
        $sms = self::where('phone', $phone)
            ->where('code', $code)
            ->where('status', 0)
            ->where('created_at', '>=', time() - 600)
            ->orderBy('id', 'desc')
            ->first();
        if ($sms) {
            if ($sms->code == $code) {
                $sms->status = 1;
                $sms->save();
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
}
